package com.example.znbk.znbklibrary.voicePlayer;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;


import com.example.znbk.znbklibrary.R;
import com.example.znbk.znbklibrary.util.TimeUtils;
import com.example.znbk.znbklibrary.util.ToastUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


public class VoicePlayer implements OnBufferingUpdateListener, OnCompletionListener,
		OnPreparedListener{

	public MediaPlayer mediaPlayer; // 媒体播放器
	private final SeekBar seekBar; // 拖动条
	private final String musicUrl;
	private final TextView tv_time;
	private final ImageButton btnPlay;
	private Timer mTimer ;
	private final String time;
	// 计时器
	private TimerTask timerTask;
	private boolean isPrepare = false;
	private boolean palyClick = false;
	private boolean isSeek = true;//是否可以拖动
	private boolean isSeekBackStart = true;//是否在播放结束后重置播放进度

	private FinishPlay finishPlay;
	private boolean isBtnPlayClickAble = false;
	public boolean getBtnPlayClickAble() {
		return isBtnPlayClickAble;
	}
	public void setBtnPlayClickAble(boolean btnPlayClickAble) {
		isBtnPlayClickAble = btnPlayClickAble;
	}

	// 初始化播放器
	public VoicePlayer(SeekBar seekBar, final String musicUrl, TextView tv_time, ImageButton btnPlay, final boolean isBtnPlayClickAble, boolean isSeek,boolean isSeekBackStart,FinishPlay finishPlay) {
		super();
		 this.time = seekBar.getContext().getResources().getString(R.string.listen_voice);
		this.tv_time = tv_time;
		this.seekBar = seekBar;
		this.musicUrl = musicUrl;
		this.btnPlay = btnPlay;
		this.isBtnPlayClickAble = isBtnPlayClickAble;
		this.isSeek = isSeek;
		this.isSeekBackStart = isSeekBackStart;
		btnPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(getBtnPlayClickAble()) {
					play();
				}
			}
		});
        seekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
		try {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
			mediaPlayer.setOnBufferingUpdateListener(this);
			mediaPlayer.setOnPreparedListener(this);
			mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e) {
			e.printStackTrace();
		}

		startTime();
		this.seekBar.setEnabled(false);
		new Thread(new Runnable() {
			@Override
			public void run() {
				playUrl(musicUrl);
			}
		}).start();

		this.finishPlay = finishPlay;

	}

	private void startTime(){
		if (mTimer == null){
			mTimer = new Timer();
		}
		if (timerTask  == null){
			timerTask = new TimerTask() {

				@Override
				public void run() {
					if (mediaPlayer == null)
						return;
					if (mediaPlayer.isPlaying() && !seekBar.isPressed()) {
						handler.sendEmptyMessage(0); // 发送消息
					}
				}
			};
			// 每一秒触发一次
			mTimer.schedule(timerTask, 0, 50);
		}
	}



	 private final Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (mediaPlayer != null) { //避免出现空指针异常
				int position = mediaPlayer.getCurrentPosition();
				int duration = mediaPlayer.getDuration();
				String currentTimeStr = TimeUtils.getTimeType1FromMillis(position);
			switch (msg.what) {
				case 0:
						if (duration > 0) {
							// 计算进度（获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长）
							long pos = seekBar.getMax() * position / duration;
							seekBar.setProgress((int) pos);
							tv_time.setText(String.format(time, currentTimeStr,
									TimeUtils.getTimeType1FromMillis(mediaPlayer.getDuration())));

						}

				break;
				case 1:
					ToastUtils.showLong("音频地址出错，无法获取音频资源");
					break;
				case 2://隔1.5秒秒跳转到开始出 免得显示突兀
					seekBar.setProgress(0);
					String currentTimeStr1 = TimeUtils.getTimeType1FromMillis(0);
					tv_time.setText(String.format(time, currentTimeStr1,
							TimeUtils.getTimeType1FromMillis(mediaPlayer.getDuration())));
					btnPlay.setBackgroundResource(R.mipmap.ic_music_play);
					break;
			}
			}
		}

	 };



	public void play() {
		palyClick = true;
		if (isPrepare) {
			if (!mediaPlayer.isPlaying()) {
				mediaPlayer.start();
				btnPlay.setBackgroundResource(R.mipmap.ic_music_pause);
			} else {
				pause();
			}
		}



	}

	public void rePlay(){
		mediaPlayer.seekTo(0);
	}

	/**
	 *
	 * @param url
	 *            url地址
	 */
	private void playUrl(String url) {
		try {
			mediaPlayer.reset();

			mediaPlayer.setDataSource(url); // 设置数据源
			mediaPlayer.prepare(); // prepare自动播放
		} catch (IllegalArgumentException | SecurityException | IOException | IllegalStateException e) {
			e.printStackTrace();
			//handler.sendEmptyMessage(1);
		}

	}

	// 暂停
	public void pause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			btnPlay.setBackgroundResource(R.mipmap.ic_music_play);
			mediaPlayer.pause();
		}
	}

	// 停止
	public void stop() {
		btnPlay.setBackgroundResource(R.mipmap.ic_music_play);
		if(timerTask != null){
			timerTask.cancel();
			timerTask = null;
		}
		if (mTimer != null){
			mTimer.cancel();
			mTimer = null;
		}

		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}


	@Override
	public void onPrepared(MediaPlayer mp) {
		tv_time.setText(String.format(time, TimeUtils.getTimeType1FromMillis(0),
				TimeUtils.getTimeType1FromMillis(mediaPlayer.getDuration())));
		isPrepare = true;
		seekBar.setEnabled(isSeek);
		if (palyClick){
			play();
		}

	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		seekBar.setProgress(seekBar.getMax());
		tv_time.setText(String.format(time, TimeUtils.getTimeType1FromMillis(mediaPlayer.getDuration()),
				TimeUtils.getTimeType1FromMillis(mediaPlayer.getDuration())));
		if(isSeekBackStart) {
			handler.sendEmptyMessageDelayed(2, 1500);
		}

		btnPlay.setBackgroundResource(R.mipmap.ic_music_play);
		finishPlay.onFinishPlay();
	}

	public interface FinishPlay{
		void onFinishPlay();
	}

	/**
	 * 缓冲更新
	 */
	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		seekBar.setSecondaryProgress(percent);

		/*if (mediaPlayer.getDuration() != 0) {
			int currentProgress = seekBar.getMax()
					* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
		}*/
		//Log.e(currentProgress + "% play", percent + " buffer");
	}

    private class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress = progress * mediaPlayer.getDuration()
                    / seekBar.getMax();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.seekTo(progress);
        }
    }

}
